package com.wang.transfer.util.algorithm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 三数之和
 * a != b b!= c a != c,a + b + c = 0
 */
public class ThreeNum {

    public static void main(String[] args) {
        int[] nums = {-1, -2, -3, -4, -5};
        List<List<Integer>> lists = new ThreeNum().threeSum(nums);
        System.out.println(lists);
    }

    public List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        for (int first = 0; first < n; ++first) {
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            int third = n - 1;
            int target = -nums[first];
            for (int two = first + 1; two < n; ++two) {
                if (two > first + 1 && nums[two] == nums[two - 1]) {
                    continue;
                }
                while (two < third && nums[two] + nums[third] > target) {
                    --third;
                }
                if (two == third) {
                    break;
                }
                if (nums[two] + nums[third] == target) {
                    List<Integer> num = new ArrayList<>();
                    num.add(nums[first]);
                    num.add(nums[two]);
                    num.add(nums[third]);
                    ans.add(num);
                }
            }
        }
        return ans;
    }
}
